package com.diorsunion.hedge.quota;

import com.diorsunion.hedge.dal.entity.stock.Stock;
import com.diorsunion.hedge.dal.entity.stock.StockPrice;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * RSI指标计算
 * rsi指标公式
 * rs = N日内收盘价涨数和之均值 / N日内收盘价跌数和之均值
 * rsi = 100-100/(1+rs);
 * 5,10,20
 * Created by harley-dog on 2016/5/3.
 */
public class RSIFilter implements StockPriceExFilter {
    public int[] n = {5,10,20};
    public RSIFilter(int n0,int n1,int n2){
        n[0] = n0;
        n[1] = n1;
        n[2] = n2;
    }

    @Override
    public void filter(Stock stock, List<StockPrice> lastList, List<StockPrice> stockPriceList) {
        int start = CollectionUtils.isEmpty(lastList)?0:lastList.size();
        List<StockPrice> stockPriceAll = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(lastList)){
            stockPriceAll.addAll(lastList);
        }
        stockPriceAll.addAll(stockPriceList);
        for(int i=0;i<n.length;i++){
            rsi(n[i],i,start,stockPriceAll);
        }
    }

    public void rsi(int n,int index,int start, List<StockPrice> stockPriceList){
        for(int i=start;i<stockPriceList.size();i++){
            StockPrice stockPrice = stockPriceList.get(i);
            double a = 0;
            double b = 0;
            int num = 0;
            for(int j=i;j>=i-(n-1) && j>=0;j--,num++){
                StockPrice s = stockPriceList.get(j);
                if(s.chg>0){
                    a+=s.chg;
                }else if(s.chg<0){
                    b-=s.chg;
                }
            }
            double rsi = (a+b)==0?50:a/(a+b)*100;
            switch (index){
                case 0:stockPrice.ex.rsi1 = rsi;
                case 1:stockPrice.ex.rsi2 = rsi;
                case 2:stockPrice.ex.rsi3 = rsi;
            }
        }
    }

}
